"""
解析数据到智图和A表
"""
import os
import shutil
import sys

import facade
from parsel import Selector
from xjlibrary.mdatetime.mtime import getTodayDate
from xjlibrary.mdatetime.mtime2 import MDateTimeUtils
from xjlibrary.our_file_dir import BaseDir
from xjlibrary.tools.BaseString import BaseString

from id_encode import GetLngid

curpath = BaseDir.get_file_dir_absolute(__file__)
TopPath = BaseDir.get_upper_dir(curpath, -2)
dirPath = BaseDir.get_new_path(TopPath, "download", "yuetongvideo", "download", "videohtml")
db3dir = BaseDir.get_new_path(TopPath, "download", "yuetongvideo", "download", "db3")
BaseDir.create_dir(db3dir)
configfile = BaseDir.get_new_path(curpath, "db.ini")
sPath = BaseDir.get_new_path(curpath, "template")


class ParaZTA(object):
    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.mysqlutils = facade.MysqlUtiles(configfile, "db", logger=self.logger)
        self.Listpara = []
        self.templatedb3 = BaseDir.get_new_path(sPath, "zt_template.db3")
        self.new_db3_path = self.copyTempDB3(self.templatedb3, db3dir)
        self.db3_zt = facade.Sqlite3Utiles(logger=self.logger).Sqlite3DBConnectFromFilePath(
            self.new_db3_path, encoding="utf-8")

    def copyTempDB3(self, temp_path, copy_out):
        """
        拷贝创建新的db3文件
        :param temp_path: 模板db3文件路径
        :param copy_out: 新的db3输出路径
        :return: 新db3路径
        """
        today_str = str(getTodayDate())
        if not os.path.isfile(temp_path) or not os.path.isdir(copy_out):
            raise FileNotFoundError
        new_db3_name = 'zt_yuetongvideo_' + today_str + '.db3'
        new_db3_path = os.path.join(copy_out, new_db3_name)
        shutil.copyfile(temp_path, new_db3_path)
        return new_db3_path

    def select_files(self):
        for file in BaseDir.get_dir_all_files(dirPath):
            print(file)
            rawid = file.split("\\")[-1].replace(".html", "")
            html = BaseDir.single_read_file(file)
            self.para_html(html, rawid)
        self.insert_db3()

    def insert_db3(self):
        sql = "insert or ignore into modify_title_info_zt (`lngid`,`rawid`,`title`,`creator`," \
              "`country`,`language`,`cover`,`provider`,`batch`," \
              "`type`,`medium`,`provider_url`,`provider_id`,`date`," \
              "`date_created`,`publisher`,`description`) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"


        self.db3_zt.ExeSqlliteMany(sql, self.Listpara)
        self.Listpara.clear()

    def select_db(self, rawid):
        sql = "select coverstat,url from video where rawid='{}'".format(rawid)
        rows = self.mysqlutils.SelectFromDB(sql)
        cover = ""
        if rows[0][0] == 1:
            cover = "/smartlib/yuetongvideo/" + rawid.lower() + ".jpg"
        return cover, rows[0][1]

    def para_html(self, html, rawid):

        cover, url = self.select_db(rawid)
        select = Selector(text=html)
        title = select.xpath('.//div[@class="minbox"]/div[@class="minboxtit"]/span/text()').get()
        title = title.strip()
        div_tag_list = select.xpath('.//div[@class="minbox"]/div[@class="minboxtit"]')
        description = ""
        author = ""
        for div_tag in div_tag_list:
            strings = "".join(div_tag.xpath(".//text()").getall())
            if strings.find("来源（作者）：") > -1:
                author = strings.replace("来源（作者）：", "").strip()
            elif strings.find("所属图书：") > -1:
                description = strings.replace("所属图书：", "").strip()

        date = "1900"
        date_created = "19000000"

        sub_db_id = "00132"
        product = "YUETONG"
        sub_db = "DMT"
        provider_zt = "yuetongvideo"
        provider = "CCPCL"

        url = "http://zt.yuetong.cn" + url
        bacth = MDateTimeUtils.get_today_date_strings() + "00"
        type_ = "10"
        medium = "2"
        provider_url = provider_zt + "@" + url
        provider_id = provider_zt + "@" + rawid
        country = "CN"
        language = "ZH"
        publisher = "人民交通出版社"

        lngid = GetLngid(sub_db_id, rawid)

        self.Listpara.append((lngid, rawid, title, author,
                              country, language, cover, provider_zt, bacth,
                              type_, medium, provider_url, provider_id, date,
                              date_created, publisher, description))


if __name__ == "__main__":
    """
    本库不解析a层
    """
    para = ParaZTA()
    para.select_files()
